package com.example.netty.normal.bytebuf.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:39
 **/
public class NormalByteBufServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NormalByteBufServerHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("收到客户端消息");
        try {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, StandardCharsets.UTF_8);
            System.out.println("-----start------|\n  " + body + " \n | ------end------");

            //发送给客户端
            String serverMsg = "++++++++我是服务端给客户端的消息+++++++";
            ByteBuf serverBuffer = ByteBufAllocator.DEFAULT.buffer();
            serverBuffer.writeBytes(serverMsg.getBytes(StandardCharsets.UTF_8));
            ctx.channel().writeAndFlush(serverBuffer);
        } catch (Exception e) {
            logger.error("接收数据异常", e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
